import Taro from '@tarojs/taro'
import {HTTP_STATUS} from './status'
import {logError} from './error'
import {baseUrl} from './baseUrl'
import {getStorage} from './localstoreage'

const whiteList = [
  '/user/getUserId',
  '/user/registerGetCode',
  '/user/registerAppUser'
]
function baseOptions<T = any>(params: any, method = 'GET') {
  return new Promise<T>((resolve, reject: (reason: boolean | T) => void) => {
    let {url, data} = params
    let contentType = params.contentType || 'application/json'
    console.log(url)
    let token: string = ''
    let userId: string = ''

    if (!whiteList.includes(url)) {
      token = getStorage('token')
      if (!token) {
        reject(false)
        return
      }

      userId = getStorage('userId')
      if (!userId) {
        reject(false)
        return
      }
    }

    // const setCookie = (res: {
    //   cookies: Array<{
    //     name: string,
    //     value: string,
    //     expires: string,
    //     path: string
    //   }>,
    //   header: {
    //     'Set-Cookie': string
    //   }
    // }) => {
    // if (res.cookies && res.cookies.length > 0) {
    //   let cookies = Taro.getStorageSync('cookies') || '';
    //   res.cookies.forEach((cookie, index) => {
    //     // windows的微信开发者工具返回的是cookie格式是有name和value的,在mac上是只是字符串的
    //     if (cookie.name && cookie.value) {
    //       cookies += index === res.cookies.length - 1 ? `${cookie.name}=${cookie.value};expires=${cookie.expires};path=${cookie.path}` : `${cookie.name}=${cookie.value};`
    //     } else {
    //       cookies += `${cookie};`
    //     }
    //   });
    //   Taro.setStorageSync('cookies', cookies)
    // }
    // if (res.header && res.header['Set-Cookie']) {
    //   Taro.setStorageSync('cookies', res.header['Set-Cookie'])
    // }
    // }
    // eslint-disable-next-line
    Taro.request({
      url: url.indexOf('http') !== -1 ? url : baseUrl + url,
      data: data,
      method: method as any,
      // 增加请求头
      header: token
        ? {
            'content-type': contentType,
            token,
            userId
          }
        : {
            'content-type': contentType
          },
      // mode: 'cors',
      // xhrFields: { withCredentials: true },
      success(res) {
        // setCookie(res)
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
          logError(`api:${url}`, '请求资源不存在')
          reject(false)
        } else if (
          [HTTP_STATUS.BAD_GATEWAY, HTTP_STATUS.SERVER_ERROR].includes(
            res.statusCode
          )
        ) {
          logError(`api:${url}`, '服务端出现了问题')
          reject(false)
        } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
          logError(`api:${url}`, '没有权限访问')
          reject(false)
        } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
          Taro.clearStorage()
          //跳转到登录页面
          logError(`api:${url}`, '请先登录')
          reject(false)
        } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
          if (res.data.result === 'success') {
            console.log(`${method}接口状态成功,接口：${url}`, res.data)
            resolve(res.data)
          } else if (res.data.result === 'error') {
            console.warn(`${method}接口状态失败,接口：${url}`, res.data)
            reject(res.data)
          } else {
            resolve(res.data)
          }
        }
      },
      fail(e) {
        logError(`api:${params.url}`, '请求接口出现问题', e)
        reject(false)
      }
    })
  })
}
export default {
  get<T = any>(url: string, data?: object): Api.Response<T> {
    return new Promise<Api.Result<T>>((resolve, reject) => {
      let option = {url, data}
      baseOptions<Api.Result<T>>(option)
        .then(res => {
          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  async post<T = any>(
    url: string,
    data?: object,
    contentType?: string
  ): Api.Response<T> {
    return new Promise<Api.Result<T>>((resolve, reject) => {
      let params = {url, data, contentType}
      baseOptions<Api.Result<T>>(params, 'POST')
        .then(res => {
          console.log(res)

          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  async put<T = any>(url: string, data?: object): Api.Response<T> {
    return new Promise<Api.Result<T>>((resolve, reject) => {
      let option = {url, data}

      baseOptions<Api.Result<T>>(option, 'PUT')
        .then(res => {
          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  async delete<T = any>(url: string, data?: object): Api.Response<T> {
    return new Promise<Api.Result<T>>((resolve, reject) => {
      let option = {url, data}
      baseOptions<Api.Result<T>>(option, 'DELETE')
        .then(res => {
          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}
